<?php

function RecursiveMkdir($path) {
	if (!file_exists($path)) {
		RecursiveMkdir(dirname($path));
		@mkdir($path, 0777);
	}
}

function upload_image($inputname, $image=null, $type='team', $width=440) 
{
	$year = date('Y'); $day = date('md'); $n = time().rand(1000,9999).'.jpg';
	$z = $_FILES[$inputname];
	if ($z && strpos($z['type'], 'image')===0 && $z['error']==0) {
		if (!$image) { 
			RecursiveMkdir( IMG_ROOT . '/' . "{$type}/{$year}/{$day}" );
			$image = "{$type}/{$year}/{$day}/{$n}";
			$path = IMG_ROOT . '/' . $image;
		} else {
			RecursiveMkdir( dirname(IMG_ROOT .'/' .$image) );
			$path = IMG_ROOT . '/' .$image;
		}
		if ($type=='user') {
			Image::Convert($z['tmp_name'], $path, 48, 48, Image::MODE_CUT);
		} 
		else if($type=='team') {
			Image::Convert($z['tmp_name'], $path, $width,0,Image::MODE_SCALE);
		}
		return $image;
	} 
	return $image;
}
function uencode($u) {
	return base64_encode(urlEncode($u));
}
function udecode($u) {
	return urlDecode(base64_decode($u));
}

function is_manager() {
	global $login_user;
	return ($login_user['manager'] == 'Y');
}


function cookie_city($city) {
	if($city) { 
		$city_v = uencode("{$city['id']}|{$city['ename']}|{$city['name']}");
		$expire = time() + 365 * 86400;
		cookieset('city', $city_v);
	} else if (!cookieget('city')) {
		$city = get_city();
		if (!$city) $city = Table::Fetch('city', 218);
		return cookie_city($city);
	} else {
		$v = explode('|', udecode(cookieget('city')));
		return array( 'id' => $v[0], 'ename' => $v[1], 'name' => $v[2],);
	}
	return $city;
}

function cookieset($k, $v, $expire=0) {
	if ($expire==0) {
		$expire = time() + 365 * 86400;
	} else {
		$expire += time();
	}
	setCookie($k, $v, $expire, '/');
}

function cookieget($k) {
	return strval($_COOKIE[$k]);
}

function get_city($ip=null) {
	global $INI;
	$hotcity_keys = array_keys($INI['hotcity']);
	$cities = DB::LimitQuery('city', array( 'cache'=>2592000,));
	$ip = ($ip) ? $ip : Utility::GetRemoteIP();
	$url = "http://open.baidu.com/ipsearch/s?wd={$ip}&tn=baiduip";
	$res = mb_convert_encoding(Utility::HttpRequest($url), 'UTF-8', 'GBK');
	$city = array();
	if ( preg_match('#来自：<b>(.+)</b>#Ui', $res, $m) ) {
		foreach( $cities AS $one ) {
			if ( FALSE !== strpos($m[1], $one['name']) ) {
				$city = $one;
				break;
			}
		}
	}
	if (!in_array($city['ename'], $hotcity_keys)) {
		return Table::Fetch('city', $hotcity_keys[0], 'ename');
	}
	return $city;
}

?>